"use client";
import React, { useMemo, useEffect, useState, useRef } from "react";
import "./index.scss";
import RtcStore from "@/app/store/rtc";
import { Human } from "@/app/api/index";
import VideoStore from "@/app/store/video";
import { parseSrt, getCurrentSubtitle } from "@/app/utils/captions";
import TheDigitalHuman from "@/app/components/TheDigitalHuman/page";

export default function Captions() {
  const { Init, setInit } = VideoStore();
  const [isPlaying, setIsPlaying] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);
  const { sessionid } = RtcStore();
  const abortControllerRef = useRef<AbortController | null>(null);
  const [flag, setFlag] = useState(false);

  useEffect(() => {
    // 组件挂载时创建新的 AbortController
    abortControllerRef.current = new AbortController(); 
    // 组件卸载时中止所有请求
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const send = async (txt: string, type = "echo") => {
    try {
      Human({
        text: txt,
        type: type,
        interrupt: false,
        sessionid: sessionid,
      }).then((res: any) => {
        console.log(res, "res");
      });
    } catch (error) {
      console.error("Request failed:", error);
    }
  };

  const togglePlay = () => {
    if (videoRef.current && !isPlaying) {
      videoRef.current.play();
      const parsedSubtitles = parseSrt(Init.Srt).map((sub) => ({
        ...sub,
        preloadTime: 0,
      }));
      Read(parsedSubtitles);
      setIsPlaying(true);
    }

    // if (videoRef.current) {
    //     if (isPlaying) {
    //       videoRef.current.pause();
    //     } else {
    //       videoRef.current.play();
    //       const parsedSubtitles = parseSrt(Init.Srt).map((sub) => ({
    //         ...sub,
    //         preloadTime: 0,
    //       }));
    //       console.log(parsedSubtitles, "parsedSubtitles");
    //       Read(parsedSubtitles);
    //     }
    //     setIsPlaying(!isPlaying);
  };

  const handleClick = () => {
    if (!flag) {
      const parsedSubtitles = parseSrt(Init.Srt).map((sub) => ({
        ...sub,
        preloadTime: 0,
      }));
      Read(parsedSubtitles);
    }
    setFlag(true);
  };

  const Read = (subtitlesData: any) => {
    const displayedSubtitles = new Set();
    let startTime = Date.now();

    const processSubtitles = () => {
      const currentTime = Date.now() - startTime;
      const currentSubtitle = getCurrentSubtitle(subtitlesData, currentTime);

      if (currentSubtitle && !displayedSubtitles.has(currentSubtitle.text)) {
        console.log("当前字幕:", currentSubtitle.text);
        displayedSubtitles.add(currentSubtitle.text);
        send(currentSubtitle.text);
        if (displayedSubtitles.size === subtitlesData.length) {
          console.log("所有字幕已显示完毕");
          cancelAnimationFrame(animationFrameId);
          return;
        }
      }
      animationFrameId = requestAnimationFrame(processSubtitles);
    };
    let animationFrameId = requestAnimationFrame(processSubtitles);
    return () => {
      if (animationFrameId) {
        cancelAnimationFrame(animationFrameId);
      }
    };
  };

  return (
    <div className="captions">
      <TheDigitalHuman width="350px" height="70%" position="right" />
      {Init.Type === "VideoUrl" && Init.VideoUrl && (
        <video
          ref={videoRef}
          className="backgroundVideo"
          src={Init.VideoUrl}
          loop // 循环播放
          muted // 静音播放
          onClick={togglePlay}
        />
      )}
      {Init.Type === "Image" && Init.Image && (
        <img
          src={Init.Image}
          className="backgroundVideo"
          alt="Background"
          onClick={() => {
            handleClick();
          }}
        />
      )}
      {Init.Type === "BackgroundColor" && (
        <div
          className="backgroundVideo"
          style={{ backgroundColor: Init.BackgroundColor }}
          onClick={() => {
            handleClick();
          }}
        />
      )}
    </div>
  );
}
